<?php

namespace App\V3\V3_2_7\Controllers;

use App\Rules\JsonArray;
use App\Services\CommonService;
use App\V3\V3_2_7\Models\MaterielProductContentModel;
use App\V3\V3_2_7\Services\ProductService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\V3\V3_2_7\Models\ProductOrderModel;

class ProductController extends BaseController
{
    /**
     * 新建生产订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @Author: Sun Wu
     * @Created at: 2022/11/23 10:53
     */
    public function add(Request $request)
    {
        $data = $request->all();
        $data['logTime'] = time();
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        $data['product_source'] = !empty($data['product_source'])?$data['product_source']:0;
        $data['product_source_id'] = empty($data['product_source_id'])?0:$data['product_source_id'];
        $data['product_way'] = empty($data['product_way'])?0:$data['product_way'];
        $data['use_batch'] = $this->getOutWay();
        $this->operateLog('创建生产任务', $data, $data['logTime']);
        return response()->json(ProductService::add($data));
    }

    /**
     * 生产订单详细
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @Author: Sun Wu
     * @Created at: 2022/11/23 10:56
     */
    public function detail(Request $request)
    {
        if(empty($request->input('id'))) {
            return $this->fail('', '无效生产订单id');
        }
        $mainId= $this->getMainUserId();
        $detail = ProductService::detail($request->input('id'), $mainId);
        if(empty($detail)) {
            return $this->fail('', '目标单据信息,没有找到！');
        }
        $data = [];
        $data['main_id'] = $mainId;
        $data['product_order_id'] = $request->input('id');
        $detail['product_schedule'] =ProductService::productSchedule($data);
        $detail = json_decode($detail,true);

        if(!empty($detail['slave_info'])){
            $slaveInfo = $detail['slave_info'];
            foreach ($slaveInfo as &$sVal){
                if(!empty($detail['slave_content'])){
                    foreach ($detail['slave_content'] as $cVal){
                        $cVal['product_slave_id'] = $sVal['id'];
                        if(!empty($sVal['is_product_materiel'])){
                            $contentId = MaterielProductContentModel::where([
                                'product_id' => $sVal['type_id'],
                                'type_id' =>$cVal['type_id']
                            ])->value('type_id');
                            if(!empty($contentId)){
                                $sVal['product_slave_content'][] = $cVal;
                            }
                        }elseif($sVal['type_id'] == $cVal['type_id']){
                            $sVal['product_slave_content'][] = $cVal;
                        }
                    }
                }
            }
            $detail['slave_info'] = $slaveInfo;
        }

        return $this->success($detail);
    }

    /**
     * 删除指定生产订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @Author: Sun Wu
     * @Created at: 2022/11/23 14:29
     */
    public function del(Request $request)
    {
        if(empty($data = $request->input('id'))) {
            return $this->fail('', '无效生产订单id');
        }
        $data['main_id'] = $this->getMainUserId();
        $res = ProductService::del($request->input('id'), $data['main_id']);
        if($res['code'] == 0){
            $productNo = ProductOrderModel::where('id',$request->input('id'))->value('product_no');
            $logData = '订单编号:'.$productNo.',已删除！';
            $this->operateLog('删除生产订单', $data, time(), $logData);
        }
        return response()->json($res);
    }

    /**
     * 生产订单列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @Author: Sun Wu
     * @Created at: 2022/11/23 15:56
     */
    public function list(Request $request)
    {
        $validator = Validator::make($data = $request->except('role_id'), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer|min:1',//当前页
            'repeal_status'=>[
                'required',
                Rule::In([0,1])
            ],//撤销状态：0-未撤销 1-已撤销
            'search_type'=>[
                'required',
                Rule::In([0,1,2,3,4,5,6])
            ],
            'status'=>[
                'required',
                Rule::In([0,1,2,3])
            ]
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`仅能为数字',
            'pageSize.min' => '`页面大小`仅能为1',
            'currentPage.required' => '`当前页大小`缺失',
            'currentPage.integer' => '`当前页`仅能为数字',
            'currentPage.min' => '`当前页`仅能为1',
            'repeal_status.required' => '`撤销状态`缺失',
            'repeal_status.in' => '`撤销状态`不合法',
            'search_type.required' => '`搜索类型`缺失',
            'search_type.in' => '`搜索类型`不合法',
            'status.required' => '`状态`缺失',
            'status.in' => '`状态`不合法',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $condition = [];
        if(!$this->getUserTpye() || !empty($this->isShareProductOrder())) {
            $condition['a.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $condition['a.user_id'] = ['EQ' => $this->getUserId()];
        }

        if($data['status'] != 0) {
            switch($data['status']) {
                case 1:
                    $condition['a.product_status'] = ['EQ' => 0];
                    break;
                case 2:
                    $condition['a.product_status'] = ['EQ' => 1];
                    break;
                case 3:
                    $condition['a.product_status'] = ['EQ' => 2];
                    break;
            }
        }

        $condition['a.is_cancel'] = ['EQ' => $data['repeal_status']];

        $keyword = empty($data['keyword'])?'':$data['keyword'];

        $startTime = '';
        $endTime = '';

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        return $this->success(
            ProductService::list($data, $condition, $keyword, $startTime, $endTime)
        );
    }

    /**
     * 撤销-当前仅未生产可进行撤销
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @Author: Sun Wu
     * @Created at: 2022/11/23 18:22
     */
    public function cancel(Request $request)
    {
        if(empty($data = $request->input())) {
            return $this->fail('', '无效生产订单id');
        }
        $data['logTime'] = time();
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $this->operateLog('生产订单撤销', $data, $data['logTime']);

        return response()->json(ProductService::cancel($data));
    }

    /**
     * 重新下单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @Author: Sun Wu
     * @Created at: 2022/11/24 11:12
     */
    public function again(Request $request)
    {
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//生产订单标识
        ],[
            'id.required' => '`生产订单标识`缺失',
            'id.integer' => '`生产订单标识`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['logTime'] = time();
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $this->operateLog('生产订单-重新下单', $data, $data['logTime']);
        return response()->json(ProductService::again($data));
    }

    /**
     * 生产订单完成
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @Author: Sun Wu
     * @Created at: 2022/11/28 10:22
     */
    public function finished(Request $request)
    {
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//生产订单标识
            'product_info' => [
                'required',
                'json',
                new JsonArray([
                    'id' => 'required|integer',//库存id
                    'num' => 'required|numeric|min:0', //数量
                ])
            ],
            'product_time' => 'required|date_format:Y-m-d H:i:s'
        ],[
            'id.required' => '`生产订单标识`缺失',
            'id.integer' => '`生产订单标识`仅能为数字',
            'product_time.required' => '请选择生产时间',
            'product_time.date_format' => '生产时间日期格式错误,仅支持例如：2008-08-08 08:08:08',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $data['logTime'] = time();
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();

        $this->operateLog('生产订单完成', $data, $data['logTime']);

        return response()->json(
            ProductService::finished($data)
        );
    }

    /**
     * 补足或还库
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     * @Author: Sun Wu
     * @Created at: 2022/11/28 13:49
     */
    public function fillOrBalance(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            /* 'task_content' => [
                'required',
                'json',
                new JsonArray([
                    'type_id' => 'required|integer',//批次id
                    'is_product_materiel' => [
                        'required',
                        Rule::in([0,1])
                    ],//库存id
                    'num' => 'required|numeric|min:0' //要使用的批次数量
                ])
            ],//生产任务 */
           /*  'materiel_content' => [
                'required',
                'json',
                new JsonArray([
                    'storage_manage_id' => 'required|integer',//库存id
                    'type_id' => 'required|integer',//商品id
                    'num' => 'required|numeric|min:0', //数量
                    'serial_info' => 'array'
                ])
            ],//原料信息 */
            'type' => [
                'required',
                Rule::in([0,1]),
            ],
        ],
            [
               /*  'task_content.required' => '参数`生产任务`缺失', */
                /* 'materiel_content.required' => '参数`原料信息`缺失', */
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['time'] = time();
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $this->operateLog('库存直接入库', $data, $data['time']);

//        $this->log('生产订单补足或还库', $data);
        $result = ProductService::fillOrBalance($data);
        CommonService::operateResult($data['user_id'], $data['time'], $result);
        return response()->json(
            $result
        );
    }

    /**
     * 生产订单出入库
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @Author: Sun Wu
     * @Created at: 2022/11/30 18:55
     */
    public function inOrOut(Request $request)
    {
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//生产订单标识
            'type' => [
                'required',
                Rule::in([3,1,2])
            ],
//            'storage_id' => 'required|integer',
//            'shelf_id' => 'required|integer',
//            'location_id' => 'required|integer',
        ],[
            'id.required' => '`生产订单标识`缺失',
            'id.integer' => '`生产订单标识`仅能为数字',
            'type.required' => '出入库类型缺失',
            'type.in' => '出入库类型不合法',
//            'storage_id.required' => '仓库id缺失',
//            'storage_id.integer' => '仓库id仅能为数字',
//            'shelf_id.required' => '货架id缺失',
//            'shelf_id.integer' => '货架id仅能为数字',
//            'location_id.required' => '库位id缺失',
//            'location_id.integer' => '库位id仅能为数字'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['use_shelf'] = $this->isUseShelf();
        $time = time();
        $this->operateLog('生产订单出入库', $data, $time);
        $data['in_storage_time'] = empty($data['in_storage_time'])?$time:strtotime($data['in_storage_time']);
        $data['label_id'] = empty($data['label_id'])?'':$data['label_id'];
        $data['label_name'] = empty($data['label_name'])?'':$data['label_name'];

        $result = ProductService::inOrOut($data, $time);
        return response()->json($result);
    }

    /**
     * 生产订单序列号列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @Author: Sun Wu
     * @Created at: 2023/1/5 16:33
     */
    public function productSerialSelect(Request $request)
    {
        return $this->success(
            ProductService::productSerialSelect($request->all(), $request->keyword)
        );
    }

    /**
     * 套件返仓序列号选择
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @Author: Sun Wu
     * @Created at: 2023/1/14 10:31
     */
    public function productReturnStorageSerialSelect(Request $request)
    {
        return $this->success(
            ProductService::productReturnStorageSerialSelect($request->all())
        );
    }

    public function balanceList(Request $request)
    {
        return $this->success(
            ProductService::balanceList($request->all())
        );
    }

    /**
     *生产进度
     * Author: zlf
     * Created at 2023/12/14 10:52
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function productSchedule(Request $request)
    {
        $validator = Validator::make($data = $request->except('role_id'), [
            'product_order_id' =>'required|integer',//生产订单标识
        ],[
            'product_order_id.required' => '`生产订单标识`缺失',
            'product_order_id.integer' => '`生产订单标识`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $data['main_id'] = $this->getMainUserId();
        $result = ProductService::productSchedule($data);
        return success($result);
    }

    /**
     *损耗
     * Author: zlf
     * Created at 2023/12/19 10:02
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function productLoss(Request $request){
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//生产订单标识
        ],[
            'id.required' => '`生产订单标识`缺失',
            'id.integer' => '`生产订单标识`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $data['time'] = time();
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $result = ProductService::productLoss($data);
        return success($result);
    }
}
